package com.rao.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

/**
 * Security 数据库用户信息配置类
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/09/06 20:23
 */
@Configuration
public class JdbcUserDetailConfig {

    //通过spring容器注入 DataSource
    @Autowired
    private DataSource dataSource;

    //创建PasswordEncoder对象
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //创建JdbcUserDetatilsService对象
    @Bean("jdbcUserDetatilsService")
    public UserDetailsService jdbcUserDetatilsService() {
        System.out.println("===dataSource===" + dataSource.toString());
        PasswordEncoder encoder = passwordEncoder();

        //初始数据源DataSource --- JdbcTemplate对象
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);

        //如果数据库中已经存在账号不添加
        if (!manager.userExists("admin")) {
            manager.createUser(User.withUsername("admin")
                    .password(encoder.encode("admin"))
                    .roles("ADMIN", "USER", "MANAGER").build());
        }

        if (!manager.userExists("zs")) {
            manager.createUser(User.withUsername("zs").
                    password(encoder.encode("123456"))
                    .roles("USER", "MANAGER").build());
        }

        if (!manager.userExists("ls")) {
            manager.createUser(User.withUsername("ls")
                    .password(encoder.encode("123456"))
                    .roles("USER").build());
        }

        return manager;
    }

}
